from itertools import groupby
from os import name
# from db.mongo import conn
from fastapi import Request
from db.es import conn
from collections import Counter
import datetime
import pandas as pd
import colorsys
import random
from model.design import design
from model.boxoffice import *


def curd_boxffice():
    return {'code': 200, 'msg': 'success', 'res': predict_boxoffice()}


def curd_design(item):
    return {'code': 200, 'msg': 'success', 'res': design(item)}


class CURD_MOVIE:
    def search_all(self):
        return conn.client.search(index='movieinfo')

    def realtime_search(self, item: Request.query_params):
        body = {
            "query": {
                "match": {
                    "movie_name": item.get('key')
                }
            },
            "collapse": {
                "field": "key_movie"
            }
        }
        data = conn.client.search(index='movieinfo', body=body).get('hits').get('hits')
        if len(data) == 0:
            return {'code': 200, 'msg': 'no similar movies'}
        else:
            res = []
            for i in data:
                name = i.get('_source').get('movie_name')
                res.append({'value': name})
            return {'code': 200, 'msg': 'success', "res": res}

    def movie_realtime_search(self, item: Request.query_params):  # 接口1
        body = {
            "query": {
                "match": {
                    "movie_name": item.get('key')
                }
            },
            "collapse": {
                "field": "key_movie"
            }
        }
        data = conn.client.search(index='moviecomment', body=body).get('hits').get('hits')
        if len(data) == 0:
            return {'code': 200, 'msg': 'no similar movies'}
        else:
            res = []
            for i in data:
                name = i.get('_source').get('movie_name')
                res.append({'value': name})
            return {'code': 200, 'msg': 'success', "res": res}

    def today_rank(self):  # 接口3
        body = {
            "query": {
                "match": {
                    "date": datetime.date.today() - datetime.timedelta(days=1)
                }
            },
            "sort": [
                {
                    "boxOffice": {"order": "desc"}
                }
            ]
        }
        data = conn.client.search(index='movieinfo', body=body, size=5).get('hits').get('hits')
        if len(data) == 0:
            return {'code': 200, 'msg': 'date not in database'}
        else:
            res = []
            for i in data:
                res.append(i.get('_source'))
            return {'code': 200, 'msg': 'success', 'res': res}

    def get_recommand(self, item: Request.query_params):  # 接口5
        body = {
            "query": {
                "match": {
                    "key_movie": item.get('key')
                }
            },
            "collapse": {
                "field": "key_movie"
            }
        }
        data = conn.client.search(index='moviecomment', body=body).get('hits').get('hits')
        if len(data) == 0:
            return {'code': 200, 'msg': 'no such movie'}
        else:
            return {'code': 200, 'msg': 'success', 'res': data[0].get('_source').get('movie_recommendation')}

    def get_homepage(self):  # 接口2，接口4也调用这个就可以,接口9也可以调这个，接口8也可以调这个
        body = {
            "query": {
                "match": {
                    "date": datetime.date.today() - datetime.timedelta(days=1)
                }
            }
        }
        data = conn.client.search(index='homepage', body=body).get('hits').get('hits')
        if len(data) == 0:
            return {'code': 200, 'msg': 'database has not today'}
        else:
            return {'code': 200, 'msg': 'success', 'res': data[0].get('_source')}

    def get_day_month(self):
        currnet = (datetime.date.today() - datetime.timedelta(days=1)).strftime("%Y-%m")
        body = {
            "query": {
                "range": {
                    "date": {
                        "gte": currnet + "-01",
                        "lte": currnet + '-31'
                    }
                }
            }
        }
        data = conn.client.search(index='movieinfo', body=body, size=100000).get('hits').get('hits')
        if len(data) == 0:
            return {'code': 200, 'msg': 'database has not today'}
        else:
            return {'code': 200, 'msg': 'success', 'res': data[0].get('_source')}

    def get_today_top5(self):  # 接口7，接口3都是一样的
        body = {
            "query": {
                "match": {
                    "date": datetime.date.today() - datetime.timedelta(days=1)
                }
            },
            "sort": [
                {
                    "boxOffice": {"order": "desc"}
                }
            ]
        }
        data = conn.client.search(index='movieinfo', body=body, size=5).get('hits').get('hits')
        temp = []
        for i in data:
            temp.append({'name': i['_source']['movie_name'], 'image': i['_source']['movie_img'],
                         'sell': i["_source"]['boxOffice']})
        for i in temp:
            body = {
                "query": {
                    "bool": {
                        "must": [
                            {
                                "match": {
                                    "date": datetime.date.today() - datetime.timedelta(days=1)
                                },
                                "match": {
                                    "movie_name": i['name']
                                }
                            }
                        ]
                    }
                }
            }
            i['score'] = \
                conn.client.search(index='moviecomment', body=body).get('hits').get('hits')[0]['_source'][
                    'movie_score'][
                    'movie_score']
        return {'code': 200, 'msg': 'success', 'res': temp}

    def get_unplay(self):  # 接口9
        body = {
            "query": {
                "match_all": {}
            },
            "sort": [
                {
                    "movie_desire": {"order": "desc"}
                }
            ]
        }
        data = conn.client.search(index='unplay', body=body, size=4).get('hits').get('hits')
        res = []
        for i in data:
            res.append(i['_source'])
        return {'code': 200, 'msg': 'success', 'res': res}

    def get_actor(self, item: Request.query_params):  # 接口13
        body = {
            "query": {
                "match": {
                    "actor": item['key']
                }
            }
        }
        data = conn.client.search(index='actor', body=body, size=100000).get('hits').get('hits')
        res = []
        for i in data:
            res.append({'value': i['_source']['actor']})
        return {'code': 200, 'msg': 'success', 'res': res}

    def get_director(self, item: Request.query_params):  # 接口13
        body = {
            "query": {
                "match": {
                    "name": item['key']
                }
            }
        }
        data = conn.client.search(index='director', body=body, size=100000).get('hits').get('hits')
        res = []
        for i in data:
            res.append({'value': i['_source']['name']})
        return {'code': 200, 'msg': 'success', 'res': res}

    def get_kind(self):  # 接口12
        body = {
            "query": {
                "match": {
                    "date": datetime.date.today()
                }
            },
            "sort": [
                {
                    "sell": {"order": "desc"}
                }
            ]
        }
        data = conn.client.search(index='kind_to_sell', body=body, size=10).get('hits').get('hits')
        res = []
        for i in data:
            res.append(i['_source'])
        return {'code': 200, 'msg': 'success', 'res': res}

    def get_detail(self, item: Request.query_params):
        name = item['name']
        body = {
            "query": {
                "match": {
                    "movie_name": name
                }
            }
        }
        movie = conn.client.search(index='moviecomment', body=body).get('hits').get('hits')[0]['_source']
        title = name
        sell = conn.client.search(index='movieinfo', body=body, size=500).get('hits').get('hits')

        imgSrc = sell[0]['_source']['movie_img']
        range = movie['movie_class'].split(',') if ',' in movie['movie_class'] else [movie['movie_class'], ]
        direction = movie['movie_country']
        length = movie['movie_length']
        time = movie['movie_date']
        score = movie['movie_score']['movie_score']
        personNum = movie['movie_score']['movie_score_count']
        introduction = movie['movie_summary']
        rank_body = {
            "query": {
                "bool": {
                    "must": [
                        {
                            "match": {
                                "movie_name": name
                            }
                        },
                        {
                            "match": {
                                "date": datetime.date.today() - datetime.timedelta(days=1)
                            }
                        }
                    ]
                }
            }
        }
        cnt = 1
        for i in conn.client.search(index='movieinfo', body=rank_body, size=20).get('hits').get('hits'):
            if i['_source']['movie_name'] == name:
                cnt += 1
                break
            cnt += 1
        ranking = cnt

        first_date = datetime.datetime.strptime(min([i['_source']['date'] for i in sell]), '%Y-%m-%d')
        print(min([i['_source']['date'] for i in sell]))
        print(first_date)
        after_week = first_date + datetime.timedelta(days=7)
        print(after_week)
        first_week_body = {
            "query": {
                "bool": {
                    "must": [
                        {
                            "match": {
                                "movie_name": name
                            }
                        },
                        {
                            "range": {
                                "date": {
                                    "gte": first_date.strftime("%Y-%m-%d"),
                                    "lte": after_week.strftime("%Y-%m-%d")
                                }
                            }
                        }
                    ]
                }
            }
        }
        data_first_week = [i['_source']['boxOffice'] for i in
                           conn.client.search(index='movieinfo', body=first_week_body, size=7).get('hits').get('hits')]
        firstWeenkend = sum(data_first_week)
        data_all_week = [i['_source']['boxOffice'] for i in sell]
        allBoxoffice = sum(data_all_week)
        today = datetime.date.today() - datetime.timedelta(days=1)
        seven_days_ago = today - datetime.timedelta(days=8)
        exchange_body = {
            "query": {
                "bool": {
                    "must": [
                        {
                            "match": {
                                "movie_name": name
                            }
                        },
                        {
                            "range": {
                                "date": {
                                    "gte": seven_days_ago,
                                    "lte": today
                                }
                            }
                        }
                    ]
                }
            }
        }
        boxofficeExchange = sum([i['_source']['boxOffice'] for i in
                                 conn.client.search(index='movieinfo', body=exchange_body, size=7).get('hits').get(
                                     'hits')])
        score_perstange = [
            {
                'value': movie['movie_score']['stars_5'],
                'name': '5'
            },
            {
                'value': movie['movie_score']['stars_4'],
                'name': '4'
            },
            {
                'value': movie['movie_score']['stars_3'],
                'name': '3'
            },
            {
                'value': movie['movie_score']['stars_2'],
                'name': '2'
            },
            {
                'value': movie['movie_score']['stars_1'],
                'name': '1'
            }
        ]
        actorSrc = movie['movie_star_info']
        comments = movie['movie_comment_info']
        movieSrc = {
            'title': title,
            'imgSrc': imgSrc,
            "range": range,
            "direction": direction,
            "length": length,
            "time": time,
            "score": score,
            "personNum": personNum,
            "introduction": introduction,
            "ranking": ranking,
            "firstWeekend": firstWeenkend,
            "allBoxoffice": allBoxoffice,
            "boxofficeExchange": boxofficeExchange,
            "score_perstange": score_perstange,
            "actorSrc": actorSrc,
            "comments": comments
        }
        return {'code': 200, 'msg': 'success', 'res': movieSrc}


curd_movie = CURD_MOVIE()
